import { ReceiveMessageType } from '/@/config/DeclareGlobal';

class ReceiveMessage {
  private eventObj: { [key: string | number]: (ev: MessageEvent) => any } = {};

  constructor() {
    window.addEventListener('message', (ev) => {
      if (this.eventObj[ev.data.type]) {
        this.eventObj[ev.data.type](ev.data);
      }
      // for (const obj in this.eventObj) {
      //   this.eventObj[obj](ev);
      // }
    });
  }
  public executeEvent(eventKey: ReceiveMessageType, data: any) {
    // debugger;
    if (this.eventObj[eventKey]) {
      this.eventObj[eventKey](data);
    }
  }

  /**
   * 添加事件监听器
   * @param eventKey - 事件的键名，用于标识事件类型，可任意填写
   * @param callback - 事件触发时调用的回调函数，接收一个 MessageEvent 类型的参数
   */
  public addListener(eventKey: ReceiveMessageType, callback: (ev: MessageEvent) => void): void {
    this.eventObj[eventKey] = callback;
  }
}

const receiveMessage: ReceiveMessage = new ReceiveMessage();
export default receiveMessage;
